package org.jeecg.modules.zhouAdmin.admin.fabeicCenter.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.pojo.*;
import org.jeecg.modules.zhouAdmin.admin.fabeicCenter.serveic.IFabricCenterService;
import org.jeecg.modules.zhouAdmin.admin.orderCenterModule.pojo.MlccCompanyInfo;
import org.jeecg.modules.zhoupackage.pojo.MlccFabricInfo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.InputStream;
import java.util.List;

/**
 * 后台面料中心Controller
 *
 * @author zxl
 * @since 20201024
 */
@RestController
@RequestMapping("/fabricCenter")
public class FabricCenterController {

    @Autowired
    IFabricCenterService service;

    /**
     * 获取面料系列列表（面料组列表）
     *
     * @param pageNo   当前页
     * @param pageSize 页面大小
     * @param status   状态
     * @param name     系列名称
     * @param price    价格
     * @param code     编号
     */
    @RequestMapping("/getGroupList")
    public Result<?> getGroupList(@RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
                                  @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                  String name, String price, String status, String code) {
        Page<FabricGroup> page = new Page<>(pageNo, pageSize);
        try {
            IPage<FabricGroup> groupList = service.getGroupList(page, name, price, status, code);
            return Result.ok(groupList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 新增面料组
     *
     * @param name   面料组名称
     * @param price  价格
     * @param remake 备注
     */
    @RequestMapping("/addGroup")
    public Result<?> addGroup(String name, Double price, String remake) {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            int result = service.addGroup(user, name, price, remake);
            if (result > 0) {
                return Result.ok("添加成功");
            } else if (result == -2) {
                return Result.error("请填写零剪价");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("面料组已存在");
        }
    }

    /**
     * 面料组编辑
     *
     * @param groupID
     * @param name
     * @param price
     * @param remake
     * @return
     */
    @RequestMapping("/updateGroup")
    public Result<?> updateGroup(Integer groupID, String name, Double price, String remake) {
        try {
            int result = service.updateGroup(groupID, name, price, remake);
            if (result > 0) {
                return Result.ok("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加失败");
        }
    }

    /**
     * 面料组下架
     *
     * @param groupID 面料组ID
     */
    @RequestMapping("/shelves")
    public Result<?> shelves(String groupID) {
        try {
            int result = service.shelves(groupID);
            if (result > 0) {
                return Result.ok("下架成功");
            } else {
                return Result.error("下架失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("下架失败");
        }
    }

    /**
     * 面料组上架
     *
     * @param groupID 面料组ID
     */
    @RequestMapping("/groupUp")
    public Result<?> groupUp(String groupID) {
        try {
            int result = service.groupUp(groupID);
            if (result > 0) {
                return Result.ok("上架成功");
            } else {
                return Result.error("上架失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上架失败");
        }
    }

    /**
     * 面料组恢复
     *
     * @param groupID 面料组ID
     */
    @RequestMapping("/huifu")
    public Result<?> huifu(String groupID) {
        try {
            int result = service.huifu(groupID);
            if (result > 0) {
                return Result.ok("上架成功");
            } else {
                return Result.error("上架失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上架失败");
        }
    }

    /**
     * 删除面料组
     *
     * @param groupID
     * @return
     */
    @RequestMapping("/deleteGroup")
    public Result<?> deleteGroup(String groupID) {
        try {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            int result = service.deleteGroup(groupID);
            if (result > 0) {
                return Result.ok("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
    }

    /**
     * 根据面料组ID获取名下面料数据列表
     *
     * @param pageNo
     * @param pageSize
     * @param groupID
     * @param fabricCode
     * @param gysCode
     * @param status
     */
    @RequestMapping("/getFabricList")
    public Result<?> getFabricList(@RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                   String groupID, String fabricCode, String gysCode, String status) {
        Page<FabricEntity> page = new Page<>(pageNo, pageSize);
        try {
            IPage<FabricEntity> list = service.getFabricList(page, groupID, fabricCode, gysCode, status);
            return Result.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 删除面料
     *
     * @param fabricID 面料ID
     * @return
     */
    @RequestMapping("/delFabric")
    public Result<?> delFabric(String fabricID) {
        int result = service.delFabric(fabricID);
        if (result > 0) return Result.ok("删除成功");
        return Result.error("删除失败");
    }


    /**
     * 下架面料
     *
     * @param fabricID 面料ID
     */
    @RequestMapping("/serFabric")
    public Result<?> serFabric(String fabricID) {
        int result = service.serFabric(fabricID);
        if (result > 0) return Result.ok("下架成功");
        return Result.error("下架失败");
    }

    /**
     * 下架的面料重新上架
     *
     * @param fabricID 面料ID
     */
    @RequestMapping("/fabricUp")
    public Result<?> fabricUp(String fabricID) {
        int result = service.fabricUp(fabricID);
        if (result > 0) return Result.ok("上架成功");
        return Result.error("上架失败");
    }

    /**
     * 获取主推面料列表
     *
     * @param pageNo     当前页
     * @param pageSize   页面大小
     * @param fabricCode 面料编号
     * @param gysCode    供应商编号
     * @param status     状态
     */
    @RequestMapping("/getFirstFabricList")
    public Result<?> getFirstFabricList(@RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                        String fabricCode, String gysCode, String status) {
        Page<FabricEntity> page = new Page<>(pageNo, pageSize);
        try {
            IPage<FabricEntity> list = service.getFirstFabricList(page, fabricCode, gysCode, status);
            return Result.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 总后台获取面料详情
     *
     * @param fabricID 面料id
     */
    @RequestMapping("/getFabricDetail")
    public Result<?> getFabricDetail(String fabricID) {
        try {
            MlccFabricInfo detail = service.getFabricDetail(fabricID);
            return Result.ok(detail);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 删除面料的恢复方式（状态变为已下架）
     *
     * @param id 面料id
     */
    @RequestMapping("/fabricHuifu")
    public Result<?> fabricHuifu(String id) {
        try {
            int i = service.fabricHuifu(id);
            if (i > 0) {
                return Result.ok("操作成功");
            } else {
                return Result.error("操作成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统异常");
        }
    }

    /**
     * 新增面料界面选择供应商
     *
     * @return
     */
    @RequestMapping("/selectGYS")
    public Result<?> selectGYS() {
        try {
            List<MySysUser> list = service.selectGYS();
            return Result.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 新增面料
     *
     * @param entity
     * @return
     */
    @RequestMapping("/addFabric")
    public Result<?> addFabric(MlccFabricInfo entity) {
        try {
            int result = service.addFabric(entity);
            if (result > 0) return Result.ok("添加成功");
            return Result.error("添加失败");
        } catch (Exception e) {
//            e.printStackTrace();
            return Result.error("面料编号已存在");
        }
    }


    /**
     * 更新面料
     *
     * @param entity
     * @return
     */
    @RequestMapping("/updateFabric")
    public Result<?> updateFabric(MlccFabricInfo entity) {
        try {
            int result = service.updateFabric(entity);
            if (result > 0) return Result.ok("修改成功");
            return Result.error("修改失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败");
        }
    }

    /**
     * 新增主推面料
     *
     * @param fabricCode 面料编号
     * @param price      添加的价格
     * @param remark     备注
     */
    @RequestMapping("/addFirstFabric")
    public Result<?> addFirstFabric(String fabricCode, double price, String remark) {
        try {
            int result = service.addFirstFabric(fabricCode, price, remark);
            if (result == -1) {
                return Result.error("面料不存在");
            } else if (result > 0) {
                return Result.ok("添加成功");
            } else {
                return Result.error("添加失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.ok("添加失败");
        }
    }

    /**
     * 删除主推面料 本质就是把面料的默认价格变成0
     *
     * @param id 面料id
     */
    @RequestMapping("/delFirstFabric")
    public Result<?> delFirstFabric(String id) {
        try {
            int result = service.delFirstFabric(id);
            if (result > 0) {
                return Result.ok("操作成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    /**
     * 删除没有发放的面料册
     *
     * @param id 面料册id
     */
    @RequestMapping("/delFabricBooklet")
    public Result<?> delFabricBooklet(String id) {
        try {
            int result = service.delFabricBooklet(id);
            if (result > 0) {
                return Result.ok("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
    }

    /**
     * 获取面料册列表
     *
     * @param pageNo   分页
     * @param pageSize 分页
     * @param name     名称
     * @param phone    电话
     */
    @RequestMapping("/listBooklets")
    public Result<?> listBooklets(@RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
                                  @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                  String name, String phone) {
        Page<MlccFabricBooklet> page = new Page<>(pageNo, pageSize);
        try {
            IPage<MlccFabricBooklet> booklets = service.listBooklets(page, name, phone);
            return Result.ok(booklets);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 新增面料册
     *
     * @param booklet
     * @return
     */
    @RequestMapping("/saveBooklet")
    public Result<?> saveBooklet(MlccFabricBooklet booklet) {
        try {
            int results = service.saveBooklet(booklet);
            if (results > 0) {
                return Result.ok("添加成功");
            }
            return Result.error("添加失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发生异常");
        }
    }

    /**
     * 更新面料册
     *
     * @param booklet 面料册对象
     */
    @RequestMapping("/updateBooklet")
    public Result<?> updateBooklet(@RequestBody MlccFabricBooklet booklet) {
        try {
            int results = service.updateBooklet(booklet);
            if (results > 0) {
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发生异常");
        }
    }

    /**
     * 面料册开始发放
     *
     * @param id 面料册id
     */
    @RequestMapping("/startfa")
    public Result<?> startfa(String id) {
        try {
            int results = service.startfa(id);
            if (results > 0) {
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发生异常");
        }
    }

    /**
     * 面料册结束发放
     *
     * @param id 面料册id
     */
    @RequestMapping("/endfa")
    public Result<?> endfa(String id) {
        try {
            int results = service.endfa(id);
            if (results > 0) {
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发生异常");
        }
    }

    /**
     * 【面料组（系列）内】面料导入excel
     *
     * @param file  上传的Excel文件
     * @param group 面料组ID
     * @return
     */
    @PostMapping("/importExcel")
    public JSONObject importExcel(MultipartFile file, String group) throws Exception {
        JSONObject jsonObject = new JSONObject();
        ImportParams params = new ImportParams();
        //表格标题所在行，计数从0开始
        params.setTitleRows(1);
        //head头部所在行，计数从0开始
        params.setHeadRows(1);
        //表格sheet数量
        //params.setSheetNum(9);
        // 最好不要设置为true，否则导入一次excel服务器会重启一次，原因不明
        //params.setNeedSave(true);
        InputStream inputStream = file.getInputStream();
        List<MlccFabricInfo> list = ExcelImportUtil.importExcel(inputStream, MlccFabricInfo.class, params);
        try {
            int result = service.importExcel(list, group);
            if (result > 0) {
                jsonObject.put("code", 0);
                jsonObject.put("msg", "导入成功");
            } else {
                jsonObject.put("code", 500);
                jsonObject.put("message", "文件中存在重复面料");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 500);
            jsonObject.put("message", e.getMessage());
        }
        return jsonObject;
    }

    /**
     * 获取面料组的阶梯折扣
     *
     * @param groupid 面料组ID
     */
    @RequestMapping("/listGroupPrice")
    public JSONObject listGroupPrice(String groupid) {
        JSONObject jsonObject = new JSONObject();
        try {
            List<MlccFabricLadderPrice> ladderPrices = service.listGroupPrice(groupid);
            jsonObject.put("code", 0);
            jsonObject.put("data", ladderPrices);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "查询失败");
        }
        return jsonObject;
    }

    /**
     * 添加折扣
     *
     * @param entity 参数对象
     */
    @RequestMapping("/saveGroupPrice")
    public JSONObject saveGroupPrice(MlccFabricLadderPrice entity) {
        JSONObject jsonObject = new JSONObject();
        try {
            int results = service.saveGroupPrice(entity);
            if (results > 0) {
                jsonObject.put("code", 0);
                jsonObject.put("msg", "添加成功");
            } else if (results == -1) {
                jsonObject.put("code", 1);
                jsonObject.put("msg", "区间与其他区间冲突，请检查");
            } else {
                jsonObject.put("code", 1);
                jsonObject.put("msg", "添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "发生异常");
        }
        return jsonObject;
    }

    /**
     * 获取面料模板
     */
    @RequestMapping("/exportFabric")
    public ModelAndView exportFabric() {
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "面料模板");
        //注解对象Class
        mv.addObject(NormalExcelConstants.CLASS, MlccFabricInfo.class);
        //自定义表格参数
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("面料模板", "面料模板文件"));
        //导出数据列表
        mv.addObject(NormalExcelConstants.DATA_LIST, service.exportFabric());
        return mv;
    }

    /**
     * 删除面料组阶梯价
     *
     * @param id 阶梯价主键id
     */
    @RequestMapping("/deleteGroupPrice")
    public JSONObject deleteGroupPrice(String id) {
        JSONObject jsonObject = new JSONObject();
        try {
            int results = service.deleteGroupPrice(id);
            if (results > 0) {
                jsonObject.put("code", 0);
                jsonObject.put("msg", "删除成功");
            } else {
                jsonObject.put("code", 1);
                jsonObject.put("msg", "操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "发生异常");
        }
        return jsonObject;
    }

    /**
     * 面料册导入面料
     *
     * @param file    上传的Excel文件
     * @param booklet 面料册ID
     */
    @PostMapping("/importBookFabricExcel")
    public JSONObject importBookFabricExcel(MultipartFile file, String booklet) throws Exception {
        JSONObject jsonObject = new JSONObject();
        ImportParams params = new ImportParams();
        //表格标题所在行，计数从0开始
        params.setTitleRows(1);
        //head头部所在行，计数从0开始
        params.setHeadRows(1);
        //表格sheet数量
        //params.setSheetNum(9);
        // 最好不要设置为true，否则导入一次excel服务器会重启一次，原因不明
        //params.setNeedSave(true);
        InputStream inputStream = file.getInputStream();
        List<MlccFabricInfo> list = ExcelImportUtil.importExcel(inputStream, MlccFabricInfo.class, params);
        try {
            int result = service.importBookFabricExcel(list, booklet);
            if (result > 0) {
                jsonObject.put("code", 0);
                jsonObject.put("msg", "导入成功");
            } else {
                jsonObject.put("code", 500);
                jsonObject.put("message", "文件中存在重复面料，已自动过滤");
            }
        } catch (Exception e) {
            jsonObject.put("code", 500);
            jsonObject.put("message", e.getMessage());
        }
        return jsonObject;
    }

    /**
     * 获取面料册下的面料列表
     *
     * @param pageNo    分页
     * @param pageSize  页面大小
     * @param bookletid 面料册id
     */
    @RequestMapping("/listFabricFromBooklet")
    public Result<?> listFabricFromBooklet(@RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") int pageSize, String bookletid) {
        Page<MlccFabricInfo> page = new Page<>();
        return Result.ok(service.listFabricFromBooklet(page, bookletid));
    }

    /**
     * 删除面料册下的面料
     *
     * @param id 关联表id
     */
    @RequestMapping("/delFabricFrombook")
    public Result<?> delFabricFrombook(String id) {
        try {
            int results = service.delFabricFrombook(id);
            if (results > 0) {
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发生异常");
        }
    }

    /**
     * 面料册详情
     *
     * @param id 面料册id
     */
    @RequestMapping("/bookletDetail")
    public JSONObject bookletDetail(String id) {
        JSONObject jsonObject = new JSONObject();
        try {
            MlccFabricBooklet results = service.bookletDetail(id);
            jsonObject.put("code", 0);
            jsonObject.put("data", results);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 1);
            jsonObject.put("msg", "发生异常");
        }
        return jsonObject;
    }

    /**
     * 公司列表
     */
    @RequestMapping("/listCompany")
    public Result<?> listCompany(@RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "4") int pageSize, String name) {
        Page<MlccCompanyInfo> page = new Page<>(pageNo, pageSize);
        return Result.ok(service.listCompany(page, name));
    }


    /**
     * 发放面料册
     *
     * @param bookletid  面料册id
     * @param remark     备注
     * @param num        发放数量
     * @param companyids 公司id
     */
    @RequestMapping("/addFa")
    public Result<?> addFa(String bookletid, String remark, Integer num, String[] companyids) {
        try {
            int results = service.addFa(bookletid, remark, num, companyids);
            if (results > 0) {
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 面料册发放情况
     *
     * @param bookletid 面料册id
     */
    @RequestMapping("/listFafang")
    public Result<?> listFafang(@RequestParam(name = "pageNo", defaultValue = "1") int pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "4") int pageSize, String bookletid) {
        Page<MlccBookletFa> page = new Page<>(pageNo, pageSize);
        return Result.ok(service.listFafang(bookletid, page));
    }

    /**
     * 删除发放记录
     *
     * @param id 发放id
     */
    @RequestMapping("/deleteFa")
    public Result<?> deleteFa(String id) {
        try {
            int results = service.deleteFa(id);
            if (results > 0) {
                return Result.ok("操作成功");
            }
            return Result.error("操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 面料列表的批量操作
     *
     * @param ids    面料id数组
     * @param status 状态
     */
    @RequestMapping("/fabricpi")
    public Result<?> fabricpi(String[] ids, Integer status) {
        try {
            int result = service.fabricpi(ids, status);
            if (result > 0) {
                return Result.ok("操作成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    /**
     * 主推面料的导入
     *
     * @param file 上传的Excel文件
     */
    @PostMapping("/importFirstFabricExcel")
    public JSONObject importFirstFabricExcel(MultipartFile file) throws Exception {
        JSONObject jsonObject = new JSONObject();
        ImportParams params = new ImportParams();
        //表格标题所在行，计数从0开始
        params.setTitleRows(1);
        //head头部所在行，计数从0开始
        params.setHeadRows(1);
        //表格sheet数量
        //params.setSheetNum(9);
        // 最好不要设置为true，否则导入一次excel服务器会重启一次，原因不明
        //params.setNeedSave(true);
        InputStream inputStream = file.getInputStream();
        List<MlccFabricInfoFirst> list = ExcelImportUtil.importExcel(inputStream, MlccFabricInfoFirst.class, params);
        try {
            int result = service.importFirstFabricExcel(list);
            if (result > 0) {
                jsonObject.put("code", 0);
                jsonObject.put("msg", "导入成功");
            } else {
                jsonObject.put("code", 500);
                jsonObject.put("message", "文件中存在重复面料");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("code", 500);
            jsonObject.put("message", e.getMessage());
        }
        return jsonObject;
    }
}
